﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace TT.Web.Controllers
{
    public class AdminController : Controller
    {
        private readonly Logic.Interfaces.ITTContext _dbContext;
        private readonly Logic.Interfaces.ITournamentGenerator _tournamentGenerator;

        public AdminController(Logic.Interfaces.ITTContext ttContext,
            Logic.Interfaces.ITournamentGenerator tournamentGenerator) {
            _dbContext = ttContext;
            _tournamentGenerator = tournamentGenerator;
        }

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(List<int> playerIds)
        {
            //get all players...
            var players = _dbContext.Players.Where(p => playerIds.Contains(p.Id)).ToList();
            //...and create tournament
            var tournament = _tournamentGenerator.CreateTournament(players);

            return Json(new { 
                id= tournament.Id, 
                link= Url.Action("Index", "Tournament", new{id=tournament.Id})
            });
        }

        public JsonResult GetPlayers() {
            var allPlayers =
                _dbContext.Players.Select(p => new
                {
                    id = p.Id,
                    label = p.FirstName
                }).ToList();
            return Json(allPlayers, JsonRequestBehavior.AllowGet);               
            
        }
    }
}
